<template>
  <div class="shortcut_setting">
    <div class="section">
      <div class="types">
        <div class="types_tabs">
          <scroll-view class="scroll-view" :scroll-x="true" style="width: 100%; white-space: nowrap; display: flex">
            <view class="item" v-for="(item, index) in typeList" :key="index" :class="active == index ? 'active' : ''"
              @click="selectTab(index, item)">
              {{ item.title }}
            </view>
          </scroll-view>
        </div>
        <div class="type_setting">
          <iconpark-icon size="32" name="menu" @click="openTypeSetting"></iconpark-icon>
        </div>
      </div>
      <div class="add_section">
        <div class="title">{{ t("add_quick_reply") }}</div>
        <div class="add_input">
          <div class="input">
            <nut-input v-model="shortCuttext" :placeholder="t('add_quick_reply') + '~'">
              <template #left>
                <div class="search_item">
                  <SelectItem @change="onSelectChange" :icon-size="14" :active="params" :options="selectOptoions" />
                </div>
              </template>
            </nut-input>
          </div>
          <Btn height="44px" v-shrink-on-click width="307px" class="btn" @click="onAddLine">{{ t("add") }}</Btn>
        </div>
      </div>
      <div class="list">
        <div class="table">
          <div class="th">
            <template v-for="(item, i) in shorcutTableHeader" :key="i">
              <div class="line" v-if="i != 0"></div>
              <div class="td" :class="'td-' + item.size">{{ item.title }}</div>
            </template>
          </div>
          <scroll-view class="main_content">
            <div class="tr" v-for="(row, index) in dataList" :key="index">
              <template v-for="(item, idx) in shorcutTableHeader" :key="item.key">
                <div class="line"></div>
                <div class="td shorcut_list_td" :class="'td-' + item.size" @click="setCurRowIndex(index)">
                  <SelectItem v-if="idx === 0" :icon-size="14" @change="onRowSelectChange" :active="row.qhcid"
                    :options="selectOptoions" />
                  <!-- 官方的不能编辑 -->
                  <nut-input v-if="idx === 1 && !row?.deviceid" v-model="row.content" :disabled="true"
                    :placeholder="t('chat_page_edit')" />
                  <nut-input v-if="idx === 1 && row?.deviceid" v-model="row.content" :disabled="!state.editing"
                    :placeholder="t('chat_page_edit')" />
                  <nut-switch v-if="idx === 2" v-model="row.istop" :disable="!state.editing" :active-value="1"
                    :inactive-value="2" inactive-color="#130a34" active-color="#0CC51E" />
                  <!-- 自动回复只能有一个 -->
                  <nut-switch v-if="idx === 3" :disable="!state.editing" @click="autospChange(row, index)"
                    v-model="row.isautorsp" :active-value="1" :inactive-value="2" inactive-color="#130a34"
                    active-color="#0CC51E" />
                  <div v-if="idx === 4 && row.deviceid" style="color: brown" @click="onDeleteLine(row, index)">
                    {{ t("delete") }}
                  </div>
                </div>
              </template>
            </div>
            <nut-empty v-if="!loading1 && !dataList?.length" :description="t('nomore_data')"></nut-empty>
          </scroll-view>
        </div>
        <div class="submit_btn">
          <Btn height="38px" v-if="!state.editing" v-shrink-on-click width="156px" class="submit edit"
            @click="onEditDataList">
            {{ t("modify") }}</Btn>
          <Btn height="38px" v-if="state.editing" v-shrink-on-click width="156px" class="submit" @click="onSaveDataList">
            {{ $t("save") }}</Btn>
        </div>
      </div>
    </div>
    <!-- 类别管理 -->
    <Modal v-model:visible="showTypeSetting" @close="getShortcutCatelist()" :title="$t('chat_page_category_man')"
      zindex="1000">
      <div class="add_type_box">
        <div class="content">
          <div class="add_type">
            <div class="text">{{ t("add_category") }}</div>
            <div class="input_box">
              <div class="input">
                <nut-input v-model="typeName" :placeholder="t('add_category')"> </nut-input>
              </div>
              <Btn height="27px" v-shrink-on-click width="68px" class="btn" @click="onAddTypeLine">{{ t("add") }}</Btn>
            </div>
          </div>
          <!-- 表格 -->
          <div class="table">
            <div class="th">
              <template v-for="(item, i) in tableHeader" :key="item.key">
                <div class="line" v-if="i != 0"></div>
                <div class="td" :class="'td-' + item.size">{{ item.title }}</div>
              </template>
            </div>
            <scroll-view class="main_content shorcut_list_td">
              <div class="tr" v-for="(row, index) in state.shortCutTyptList" :key="index + row.title">
                <template v-for="(item, idx) in tableHeader" :key="item.key">
                  <div class="line"></div>
                  <div class="td" :class="'td-' + item.size">
                    <nut-input v-if="idx === 0" v-model="row.title" :disabled="!row.deviceid ? true : false"
                      :placeholder="t('chat_page_edit')" />
                    <div v-if="idx === 1">{{ row.num || 0 }}</div>
                    <div v-if="idx === 2 && !row?.num && row.deviceid" style="color: brown"
                      @click="deleteTypeLine(row, index)">
                      {{ t("delete") }}
                    </div>
                  </div>
                </template>
              </div>
              
              <nut-empty v-if="!loading && !state.shortCutTyptList.length" :description="t('nomore_data')"></nut-empty>
            </scroll-view>
          </div>
          <div class="submit_btn">
            <Btn height="38px" v-shrink-on-click width="100%" class="submit" @click="onSaveTypeList">{{ $t("save") }}
            </Btn>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted, watch, defineAsyncComponent } from "vue";
import { useI18n } from "vue-i18n";
import protobuf from "protobufjs";
import usechatHooks from "./useHooks.ts";
import IWebsocket from "../chatWS.ts";
import { showToast } from "@nutui/nutui";
import { useRoute, useRouter } from "vue-router";
import { showDialog } from "@nutui/nutui";
import { Local } from "@/utils/storage";
import { storeToRefs } from "pinia";
import { User } from "@/store/user";

const SelectItem = defineAsyncComponent(() => import("@/components/SelectItem.vue"));

const route = useRoute();
const { t } = useI18n();
const { roleInfo } = storeToRefs(User());
const router = useRouter();

const state: any = reactive({
  root: null,
  deviceID: roleInfo.value.id, // roleInfo.value.id,
  requestid: 5000, // 对方id
  todeviceid: 2655337, //对方设备ID
  shortCutTyptList: [],
  quickPhrasesList: [],
  editing: false,
  canGoBack: true,
});
const {
  getShortcutCateMsg,
  getShortcutCatelist,
  getShortcutMsg,
  getShortcutlist,
  setShortcutList,
  setShortcutCateList,
  decodeContent,
}: any = usechatHooks(state);
// tabs
let active = ref(0);
const showTypeSetting = ref(false);
const typeList = computed(() => {
  params.value = state.shortCutTyptList[0]?.id;
  console.log("shortCutTyptList", state.shortCutTyptList);
  let arr = [...state.shortCutTyptList];
  arr.unshift({ title: t("all"), id: "0" });
  return arr;
});
let dataList = ref(state.quickPhrasesList);
let selectedTabId = ref(null);
let dataListCopy = ref(state.quickPhrasesList);
watch(
  () => state.quickPhrasesList,
  (n) => {
    if (n.length) {
      dataListCopy.value = n;
      dataList.value =
        active.value === 0
          ? n
          : dataListCopy.value.filter((it: any) => it.qhcid === selectedTabId.value);
    }
  }
);
const selectTab = (index: any, item: any) => {
  selectedTabId.value = item.id;
  active.value = index;
  dataList.value =
    item.id === "0"
      ? [...dataListCopy.value]
      : dataListCopy.value.filter((it: any) => it.qhcid === item.id);
};
const openTypeSetting = () => {
  showTypeSetting.value = true;
  typeName.value = "";
  getShortcutCatelist();
};
// 添加快捷用语
// const selectOptoions = [
//   { label: '充值', value: 1 },
//   { label: '来访', value: 2 },
// ]
const selectOptoions = computed(() => {
  let arr = [];
  arr = state.shortCutTyptList.map((item: any) => {
    return {
      label: item.title,
      value: item.id,
    };
  });
  return arr;
});
const params: any = ref(0);
const onSelectChange = (value: any) => {
  // 切换下拉
  params.value = value;
};
const shortCuttext = ref("");
const rowIndex = ref(0);
const onAddLine = () => {
  const obj = {
    content: shortCuttext.value,
    mType: 16, // 16 新增，17 修改，18 删除
    qhcid: params.value, // 分类id
    istop: 2, //1 为置顶 其余值不置顶
    isautorsp: 2, //是否是自动回复 前端用的
  };
  if (!obj.content.trim()) {
    showToast.fail(t("content_required") + "!");
    return;
  }
  dataList.value.unshift(obj);
  shortCuttext.value = ""; // 清空
};

const onDeleteLine = async (row: any, index: any) => {
  if (!state.editing) return;
  console.log("rowl", row);
  showDialog({
    title: t("tip"),
    content: t("confirm_delete"),
    okText: t("confirm"),
    cancelText: t("cancel"),
    onOk: async () => {
      if (row.id) {
        const params = {
          ...row,
          mType: 18, // 16 新增，17 修改，18 删除
        };
        setDataList(params);
      } else {
        dataList.value.splice(index, 1);
      }
    },
  });
};
const onEditDataList = () => {
  state.editing = true;
};
const onSaveDataList = () => {
  // 先遍历校验再请求
  let cansave = true;
  dataList.value.map((item: any) => {
    if (!item.content.trim()) {
      cansave = false;
    }
  });
  if (!cansave) {
    showToast.text(t("content_required") + "!");
    return;
  }
  let list = <any>[];
  // 在某分组中设置自动回复，源数据的自动回复都要变更：如果自动回复item变更，将之前总list的自动回复的找出来设置为0再push进dataList
  if (isautorspId.value) {
    dataListCopy.value.map((item: any) => {
      if (item.isautorsp == 1 && item.id !== isautorspId.value) {
        item.isautorsp = 2;
        list.push(item);
      }
    });
  }
  list = list.length > 0 ? [...list, ...dataList.value] : [...dataList.value];
  console.log(333333333, list, dataList.value);
  list.map((item: any) => {
    if (item.id) {
      const params = {
        ...item,
        mType: 17, // 16 新增，17 修改，18 删除
      };
      setDataList(params);
    } else {
      // 这是新增的数据
      const params = {
        ...item,
        mType: 16,
      };
      setDataList(params);
    }
  });
};
// 新增编辑删除快捷语
const setDataList = (data: any) => {
  const params = {
    ...data,
  };
  setShortcutList(params);
};

// 类别管理
const typeName = ref("");
const onAddTypeLine = () => {
  const obj = {
    title: typeName.value,
    mType: 20, // 20 新增，21 修改，22 删除
  };
  if (!obj.title.trim()) {
    showToast.fail(t("content_required") + "!");
    return;
  }
  state.shortCutTyptList.unshift(obj);
  typeName.value = ""; // 清空
};
const onSaveTypeList = () => {
  state.shortCutTyptList.map((item: any) => {
    if (item.id) {
      const params = {
        ...item,
        mType: 21, // 20 新增，21 修改，22 删除
      };
      setShortTypeList(params);
    } else {
      // 这是新增的数据
      const params = {
        ...item,
        mType: 20, // 20 新增，21 修改，22 删除
      };
      setShortTypeList(params);
    }
  });
};
const deleteTypeLine = (row: any, index: any) => {
  console.log("rowl", row);
  showDialog({
    title: t("tip"),
    content: t("confirm_delete"),
    okText: t("confirm"),
    cancelText: t("cancel"),
    onOk: async () => {
      if (row.id) {
        const params = {
          ...row,
          mType: 22, // 20 新增，21 修改，22 删除
        };
        setShortTypeList(params);
      } else {
        state.shortCutTyptList.splice(index, 1);
      }
    },
  });
};
const setShortTypeList = (data: any) => {
  const params = {
    ...data,
  };
  setShortcutCateList(params);
};

const loading = ref(false);
const tableHeader = computed(() => {
  return [
    // 表头
    { title: t("category"), key: "type", size: "x" },
    { title: t("quick_reply_count"), key: "count", size: "s" },
    { title: t("operation"), key: "options", size: "s" },
  ];
});

// 快捷语表格
const shorcutTableHeader = computed(() => {
  return [
    // 表头
    { title: t("type"), key: "type", size: "x" },
    { title: t("quick_reply"), key: "text", size: "x" },
    { title: t("top"), key: "top", size: "s" },
    { title: t("auto_reply"), key: "auto_reply", size: "s" },
    { title: t("operation"), key: "options", size: "s" },
  ];
});
const loading1 = ref(false);
const setCurRowIndex = (index: any) => {
  rowIndex.value = index;
  console.log("rowindex", index);
};
const onRowSelectChange = (value: any) => {
  // 切换行下拉
  if (!state.editing) return;
  dataList.value[rowIndex.value].qhcid = value;
  // resetData()
};
const isautorspId = ref();
const autospChange = (row: any, index: any) => {
  // 切换行下拉
  // 遍历整个列表，确保其他行的isautorsp都被设为关闭状态(2)
  dataList.value.forEach((item: any, i: any) => {
    if (dataList.value[index].isautorsp == 1 && index == i) {
      isautorspId.value = row.id;
    } else if (index !== i && dataList.value[index].isautorsp == 1) {
      // 确保不修改当前行
      item.isautorsp = 2; // 设置其他行为关闭状态
    }
  });
};
const onMessage: any = async (buffer: any) => {
  const decodeobj1 = decodeContent(buffer, "Output");
  console.log("onMessage/Output output0 ", decodeobj1);
  state.messageType = decodeobj1.type;
  if (decodeobj1.code && decodeobj1.code > 1000) {
    showToast.fail(t(decodeobj1.code));
    return;
  }
  switch (decodeobj1.type) {
    case 23: //快捷语分类
      getShortcutCateMsg(decodeobj1);
      break;
    case 19: //快捷列表数据
      getShortcutMsg(decodeobj1);
      break;
    case 16:
    case 17:
    case 18: //快捷列表编辑
      getShortcutlist();
      showToast.text(t("operation_success"));
      if (!state.canGoBack) return;
      router.push(Local.get('chatRoomUrl'))
      setTimeout(() => (state.canGoBack = false), 0);
      setTimeout(() => (state.canGoBack = true), 2000);
      break;
    case 20:
    case 21:
    case 22: //快捷类型编辑
      showToast.text(t("operation_success"));
      // showTypeSetting.value = false
      getShortcutCatelist();
      break;

    default:
      break;
  }
};
// 编码发送参数
const encodeParams = (params: any, name: string) => {
  let item = state.root.lookupType(name);
  const errMsg = item.verify(params);
  if (errMsg) throw new Error(errMsg);
  const message = item.create(params);
  const buffer = item.encode(message).finish();
  return buffer;
};
const onOpen = () => {
  let token = Local.get('token')
  const type = 1; // PT_SIGN_IN
  const requestid = 5000;
  const singin = {
    deviceid: state.deviceID, //用户的roleid
    userid: state.deviceID, //用户的roleid
    token, // Local.get('user').token,//后期从另外一个项目中获取
  };
  const data = encodeParams(singin, "SignInInput");
  const params = {
    type: type,
    requestid: requestid,
    data: data,
  };
  const encodedRequest = encodeParams(params, "Input");
  IWebsocket.sendMessageHandler(encodedRequest);
};
onMounted(async () => {
  const roleInfo =
    (localStorage.getItem("roleInfo") && JSON.parse(localStorage.getItem("roleInfo")!)) ||
    {};
  state.deviceID = Number(roleInfo.id || Local.get("deviceid"));
  // state.userData = JSON.parse(route.query.userInfo as string)
  // state.todeviceid = state.userData.Tdeviceid
  // state.type = route.query.type
  state.requestid = route.query.requestid;
  // state.chatMessagesList = []
  // console.log('进入,selectedchatItem', state.userData)
  if (IWebsocket.instance == null) {
    IWebsocket.conectWebsocket();
  }
  state.root = await protobuf.load("/connect.ext.proto");
  onOpen();
  IWebsocket.resgisterHandler(onMessage);
  // 获取
  getShortcutCatelist();
  getShortcutlist();
});
</script>

<style lang="scss" scoped>
@use "../common/table.scss";

.shortcut_setting {
  margin-top: 10px;
}

.section {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 85px - env(safe-area-inset-top));
  padding: 0 10px 0;
  color: #8e82c2;

  .types {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 36px;
    flex-grow: 0;
    padding: 5px 0 5px 6px;

    .types_tabs {
      width: 100%;
      overflow: hidden;

      .scroll-view {
        .item {
          display: inline-block;
          margin: 4px;
          font-size: 14px;
          color: #C6C4F5;
          padding: 4px 10px 13px;
          position: relative;

          &.active {
            color: #5B6CFF;

            &::after {
              content: '';
              position: absolute;
              bottom: 0;
              left: 0;
              width: 100%;
              height: 2px;
              background: linear-gradient(180deg, #5B6CFF 0%, #9E1EFF 100%);
            }
          }
        }
      }
    }

    .type_setting {
      margin-left: 4px;
      padding: 0 0 0 5px;
      display: flex;
      align-items: center;
      margin-top: -8px;
    }
  }

  .add_section {
    .title {
      margin-bottom: 10px;
      font-size: 12px;
      text-align: left;
      color: #fff;
      font-weight: 500;
    }

    .add_input {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;

      .input {
        width: 100%;
      }

      &:deep(.nut-input) {
        width: 100%;
        height: 48px;
        padding: 0px 8px;
        border-radius: 8px;
        border: solid 1px #322c59;
        background-color: #1f2032;
        line-height: 28px;
        display: flex;
        align-items: center;

        input {
          &::placeholder {
            color: #8d84c5;
          }
        }
      }

      .btn {
        width: 307px;
        margin-top: 15px;
        border-radius: 8px;
        overflow: hidden;
      }

      :deep(.search_item) {
        height: 28px;
        min-width: 72px;
        border-radius: 8px;
      }

      :deep(.select_item) {
        background: #32305F;
        box-shadow: 0.5px 0.5px 1px 0px #595794 inset;

        .label {
          max-width: 80px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: inline-block;
          margin-right: 4px !important;
        }
      }
    }
  }

  .list {
    flex-grow: 1;
    margin-top: 14px;
    padding-bottom: 64px;
    display: flex;
    flex-direction: column;
    overflow: auto;
    max-height: 100%;

    .table {
      flex-grow: 1;
    }

    .main_content {
      :deep(.content) {
        border-radius: 8px;
        overflow: hidden;
      }

      .shorcut_list_td {
        :deep(.select_item) {
          width: 80px;
          height: 30px;
          padding: 0px 4px;
          background: #32305F;
          box-shadow: 0.5px 0.5px 1px 0px #595794 inset;

          span {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 80px;
          }

          .label {
            margin-right: 0 !important;
          }
        }

        :deep(.nut-input) {
          height: 32px;
          padding: 4px 10px;
          border-radius: 8px;
          border: solid 1px #322c59;
          background-color: transparent;

          input {
            &::placeholder {
              color: #8d84c5;
              font-size: 10px;
            }
          }
        }

        :deep(.nut-switch.nut-switch-base) {
          height: 16px;

          .nut-switch-button {
            background: #EBF0F7;
            width: 16px;
            height: 16px;
            margin-left: -4px;
          }

          &.nut-switch-open {
            background-color: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
            border-radius: 8px;
            background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);

          }
        }
      }
    }
  }
}

.add_type_box {
  color: #fff;

  .content {
    display: flex;
    flex-direction: column;
    max-height: 80vh;
    padding: 10px 20px 20px;

    .add_type {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      margin: 14px 0;

      .text {
        width: 100%;
        font-size: 12px;
        color: #fff;
      }

      .input_box {
        width: 100%;
        margin-top: 8px;
        display: flex;
        align-items: center;
        gap: 10px;

        .btn {
          height: 44px;
          justify-content: center;
          align-items: center;
          font-size: 14px;
        }
      }

      .input {
        flex: 1;
      }

      &:deep(.nut-input) {
        height: 48px;
        padding: 0px 8px;
        border-radius: 8px;
        border: solid 1px #322c59;
        background-color: #1f2032;
        line-height: 28px;
        display: flex;
        align-items: center;

        input {
          &::placeholder {
            color: #504F6F;
            font-size: 14px;
            font-weight: 400;
          }
        }

      }
    }
  }

  :deep(.nut-input) {
    height: 32px;
    padding: 4px 10px;
    border-radius: 8px;
    border: solid 1px #322c59;
    background-color: transparent;

    input {
      &::placeholder {
        color: #8d84c5;
        font-size: 10px;
      }
    }
  }

  :deep(.nut-switch.nut-switch-base) {
    height: 16px;

    .nut-switch-button {
      background: #EBF0F7;
    }
  }

  .submit_btn {
    width: 100%;
  }
}

:deep(.nut-popup) {
  z-index: 1000 !important;
  background: red;
}

:deep(.nut-overlay) {
  z-index: 1000 !important;
}

.submit_btn {
  width: 100%;
  height: 44px;
  padding: 24px 0 40px;
  display: flex;
  justify-content: space-around;

  color: #FFF;
  font-size: 14px;
  font-weight: 500;

  .edit {
    border-radius: 8px;
    background: #282747;
    box-shadow: 0.5px 0.5px 1px 0px #4B4A6E inset;
  }
}
</style>
